/**
 * @Title: index.js
 * @Description: index
 * @author: Fanchao
 * @date: 2020/9/19 4:29 下午
 * @version V1.0
 */
import React, { useEffect, useState, useRef } from 'react';
import styles from './index.less';
import { Input, Form, Button, Table, DatePicker, Select, Cascader, Popconfirm, message, Drawer, Tag, Tabs } from 'antd';
import { connect } from 'umi';
import { ExclamationCircleFilled } from '@ant-design/icons'
import cx from 'classnames'
import moment from 'moment'
import { reqUsersList, reqForbidUser, reqUserDetail, reqUserRefuse } from '@/services/index';
import UserDrawer from './components/UserDrawer'
import ReportDrawer from './components/ReportDrawer'
import { tdist } from '@/utils'

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs

const sexMap = {
    'M': '男',
    'F': '女',
    'NONE': '未知'
};

const User = () => {
    const reportRef = useRef(null)
    const userRef = useRef(null)
    const [form] = Form.useForm();
    const [list, setList] = useState([]); // 列表
    const [total, setTotal] = useState(0); // 数据总量
    const [offset, setOffset] = useState(0); // 分页
    const [loading, setLoading] = useState(false); // 加载

    const [keyword, setkeyword] = useState(''); // 关键词
    const [range, setRange] = useState([]); // 时间
    const [banned, setBanned] = useState(-1); // 是否禁用
    const [options, setOptions] = useState([]); // 省市变量
    const [province, setProvince] = useState([]); // 省市筛选

    const [certificated, setCertificated] = useState('');
    const [userInfo, setUserInfo] = useState({});
    const [currentUser, setCurrentUser] = useState({});

    useEffect(() => {
        getData()
    }, [keyword, offset, range, banned, province, certificated])

    useEffect(() => {
        let s = tdist.getLev1();
        s = s.map(one => {
            let ss = tdist.getLev2(one.id);
            one.children = ss;
            return one
        })
        setOptions(s);
    }, [])

    const getData = () => {
        setLoading(true);
        let params = {}
        const option = {
            created_time: range.length ? [moment(range[1]).unix() * 1000, moment(range[2]).unix() * 1000] : [],
            province
        }
        if (banned != -1) option.banned = !banned;

        params = {
            keyword,
            offset,
            limit: 10,
            certificated,
            searchOptions: JSON.stringify(option)
        }
        if (!certificated) delete params.certificated
        reqUsersList(params).then(({ data }) => {
            setList(data.list);
            setTotal(data.total);
            setLoading(false);
        })
    }

    const search = (e) => {
        setkeyword(e.target.value);
    };
    const empty = () => {
        form.resetFields();
        setkeyword('');
        setBanned(-1)
        setRange([])
        setOptions([])
        setProvince([])
        setCertificated('')
        setOffset(0);
    };
    const searchByOffset = (offset) => {
        setOffset(offset);
    };
    const dateChange = (date, dateString) => {
        setRange(dateString);
        setOffset(0);
    }
    const selectChange = (value) => {
        setBanned(value);
        setOffset(0);
    }
    const locationChange = (value) => {
        setProvince(value);
        setOffset(0);
    }
    const certiChange = (value) => {
        setCertificated(value);
        setOffset(0);
    }

    const handleForbid = (item) => {
        reqForbidUser({
            user_id: item.user_id,
            banne: !item.banned
        }).then((res) => {
            message.success(res.message)
            getData();
        })
    }

    const handleShowDetail = (item) => {
        // testid: cf633380-0b7b-11eb-afa2-933e7e3bdc98
        userRef.current && userRef.current.open()
        setCurrentUser(item);
        reqUserDetail({
            user_id: item.user_id
        }).then(res => {
            setUserInfo(res.data);
        })
    }

    const handleRefuse = (type, remark) => {
        reqUserRefuse({
            user_id: currentUser.user_id,
            operate: type,
            rejectContent: remark
        }).then(res => {
            message.info(res.message);
        })
    }

    const handleShowReport = (item) => {
        setCurrentUser(item);
        reportRef.current && reportRef.current.open();
    }
    const columns = [
        {
            title: '用户',
            align: 'left',
            render: (item) => {
                return (
                    <>
                        <img
                            style={{ width: '40px', height: '40px', borderRadius: '50%', marginRight: '10px' }}
                            src={item.avatar} alt=""
                        />
                        {item.nick_name}
                    </>
                );
            },
        },
        {
            title: '空置天数',
            align: 'left',
            render: (item) => <span>{item.loginAt ? moment(item.loginAt).fromNow() : '-'}</span>
        },
        {
            title: '性别',
            align: 'left',
            render: (item) => <div>{sexMap[item.sex]}</div>
        },
        {
            title: '手机号',
            dataIndex: 'mobile',
            align: 'left',
        },
        {
            title: '生日',
            dataIndex: 'birthday',
            align: 'left',
        },
        {
            title: '邮箱',
            align: 'left',
            render: (item) => <span>{item.email || '-'}</span>
        },
        {
            title: '实名认证',
            align: 'left',
            render: (item) => <span>{item.certificated ? '是' : '否'}</span>
        },
        {
            title: '创建时间',
            align: 'left',
            render: (item) => <span>{moment(item.create_time).format('YYYY-MM-DD HH:mm')}</span>
        },
        {
            title: '地址',
            // dataIndex: "enterSchoolTime",
            align: 'left',
            render: (item) => {
                return (
                    <div>
                        {`${item.province} ${item.city}`}
                    </div>
                );
            },
        },
        {
            title: '操作',
            // dataIndex: "enterSchoolTime",
            align: 'left',
            render: (item) => {
                return <div>
                    {
                        !item.banned
                            ? <Popconfirm
                                title="此操作将禁用该用户，是否继续？"
                                onConfirm={() => handleForbid(item)}
                                okText="确定"
                                cancelText="取消"
                            >
                                <span style={{ cursor: 'pointer', color: '#2866DE' }}>封禁</span>
                            </Popconfirm>
                            : <Popconfirm
                                title="此操作将解封该用户，是否继续？"
                                onConfirm={() => handleForbid(item)}
                                okText="确定"
                                cancelText="取消"
                            >
                                <span style={{ cursor: 'pointer', color: '#13CE66' }}>解封</span>
                            </Popconfirm>
                    }
                    <span onClick={() => handleShowDetail(item)} style={{ marginLeft: 10, cursor: 'pointer', color: '#2866DE' }}>详情</span>
                    { item.beReport ? <ExclamationCircleFilled onClick={() => handleShowReport(item)} style={{ marginLeft: 10, color: 'red', cursor: 'pointer' }} /> : null }
                </div>
            },
        },
    ];
    console.log('range', range)
    return (
        <div className={styles.pageContainer}>
            <div className={styles.pageContainerFilter}>
                <Form
                    layout="inline"
                    form={form}
                >
                    <Form.Item
                        label="关键字"
                        name="keyword"
                    >
                        <Input placeholder="用户名、手机号" onPressEnter={search} />
                    </Form.Item>
                    <Form.Item>
                        <RangePicker
                            style={{ marginRight: '16px' }}
                            onChange={dateChange}
                            value={range.length ? [moment(range[0]), moment(range[1])] : range}
                        />
                        <Select value={banned} style={{ width: 80 }} onChange={selectChange} options={[
                            { label: '全部', value: -1 }, { label: '封禁', value: 0 }, { label: '未封禁', value: 1 },
                        ]} />
                        <Select value={certificated} style={{ width: 120 }} onChange={certiChange} options={[
                            { label: '全部', value: '' }, { label: '认证通过', value: 'approve' }, { label: '未实名', value: 'not' }, { label: '认证被拒绝', value: 'reject' }, { label: '待审核', value: 'unreviewed' }
                        ]} />
                        <Cascader options={options} style={{ width: 120 }} value={province} onChange={locationChange} placeholder="请选择省市区" />
                        {/* <Button type="primary" style={{ margin: '0 16px' }} onClick={search}>查询</Button> */}
                        <Button type="primary" style={{ marginLeft: '16px' }} onClick={empty}>清空</Button>
                    </Form.Item>
                </Form>
            </div>
            <div className={styles.pageContainerTable}>
                <Table
                    bordered={false} // 是否有边框
                    rowKey='user_id' // 唯一key值
                    loading={loading} // 加载动画
                    columns={columns} // 表头
                    dataSource={list}
                    pagination={{
                        current: offset + 1,
                        total: total,// 总记录数
                        defaultPageSize: 10, // 默认显示条数
                        showQuickJumper: true, // 快速跳转
                        // showSizeChanger: true, // 一页展示数据条数
                        onChange: (offset) => searchByOffset(offset - 1),
                        showTotal: () => {
                            return `共${total}条`;
                        },
                    }}
                />
            </div>
            <UserDrawer ref={userRef} data={userInfo} user={currentUser} onOk={handleRefuse} />
            <ReportDrawer ref={reportRef} user={currentUser} />
        </div>
    );
};

export default User
